package com.rosense.nfvo.service.impl;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.rosense.common.Hive_Utils;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.springframework.stereotype.Service;


import com.rosense.commons.LangUtils;
import com.rosense.nfvo.common.JsonResultUtil;
import com.rosense.nfvo.service.NfvoService;
import com.rosense.nfvo.util.CallMsgsHdfsQuery;
import com.rosense.nfvo.util.DateUtils;
import com.rosense.nfvo.util.Kbs2HbaseUtil;
import com.rosense.nfvo.util.LteCallMsgsHdfsQuery;
import com.rosense.sa.bean.Call;
import com.rosense.sa.bean.SaCallConfigV1;
import com.rosense.sa.bean.SaMessage;
import com.rosense.volte.bean.LteCall;
import com.rosense.volte.bean.LteCallConfigV1;
import com.rosense.volte.bean.LteMessage;
import java.sql.*;



@Service("nfvoService")
public class NfvoServiceImpl implements NfvoService {
/*
    @Override
    public String getToken(String json) {
        String userName = "nfvo_oss";
        String value = "NfvoOss123!@#";
        JSONObject object = JSONObject.parseObject(json);
        String name = object.get("username").toString();
        String pwd = object.get("password").toString();
        if(name.equals(userName) && pwd.equals(value)){
            System.out.println(new Date() + " 有用户"+json+" 已连接");
            return JSONObject.toJSONString(JsonResultUtil.getJson(name + pwd + json.hashCode()));
        }else{
            return JSONObject.toJSONString(JsonResultUtil.getJson(400,"用户名密码错误","{}"));
        }
    }

	@Override
    public String doTestPort(String json) {
		// TODO Auto-generated method stub		
	    JSONObject object = JSONObject.parseObject(json);
		Object id = object.get("conn");
		 JSONObject success = new JSONObject();				
		 success.put("hello", id.toString());			 
		return success.toJSONString();
	}


	*/
	@Override
	public String getTraceData(String json) {
		// TODO Auto-generated method stub
		   String jsonString="";
			 
		   List<Map<String, Object>> result = new ArrayList<Map<String,Object>>();
		   Connection conn=null;
	try {
		
		 JSONObject object = JSONObject.parseObject(json);
		
			  Object imsi = object.get("imsi");
			  Object stime = object.get("stime");//开始时间
			  Object etime = object.get("etime");//结束时间
			  Object net_type = object.get("nettype");//网络制式

			  System.out.println(imsi.toString());
			  System.out.println(stime.toString());
			  System.out.println(etime.toString());
			  System.out.println(net_type.toString());
	    	  long imsi_new=LangUtils.toLong(imsi.toString(), 0);
		      long time_start=DateUtils.parseDateFormat(stime.toString(), "yyyyMMddHHmm").getTime();
			  long time_end=DateUtils.parseDateFormat(etime.toString(), "yyyyMMddHHmm").getTime();
			  conn = Kbs2HbaseUtil.getConnection();
			  if(net_type.toString().equalsIgnoreCase("4G")) {
			   LteCallConfigV1 callconfig=LteCallConfigV1.config.getInstance((short)0);
				
			   List<LteCall> calls=new ArrayList<LteCall>();
			  
				 String tableName=Constants.HBASE_TBLNAME_IMSI_4G;
				 String	startrow=(Constants.HBASE_TBLNAME_IMSI_partition_start_4G
							+ imsi_new % Constants.HBASE_TBLNAME_IMSI_partition_4G) + "_" + imsi_new
							+ "_" + time_start;
				 String	endrow=(Constants.HBASE_TBLNAME_IMSI_partition_start_4G
							+ imsi_new % Constants.HBASE_TBLNAME_IMSI_partition_4G) + "_" + imsi_new
							+ "_" + time_end;
				System.out.println("startrow*****"+startrow);
				System.out.println("endrow*****"+endrow);
				
				System.out.println("tableName****"+tableName);
				 Table table = conn.getTable(TableName.valueOf(tableName));
		            Scan scan = new Scan();
		            scan.setStartRow(startrow.getBytes());
		            scan.setStopRow(endrow.getBytes());
		            ResultScanner scanner = table.getScanner(scan);
		            int cellCount=0;
		            for (Result results : scanner) {
		            	String rowkey=new String(results.getRow());
		            	
		                for (Cell cell : results.rawCells()) {
		                    String row = cell.toString().split(":")[1].split("/")[0];
		                    byte[] bytes=CellUtil.cloneValue(cell);
		                    ByteBuffer byteBuf = ByteBuffer.wrap(bytes);
		                    LteCall call=new LteCall(callconfig,byteBuf);
		                    calls.add(call);
		                }
		            }
				
				
				
				for(LteCall call:calls) {
			//		System.out.println(call.toCallLine_m(Constants.sep, callconfig));
					Map<String, Object> map=new HashMap<>();
					map.put("result",call.toCallLine_m(Constants.sep, callconfig));
					result.add(map);
				}
				
			  }else if(net_type.toString().equals("5G")) {
				  SaCallConfigV1 callconfig=SaCallConfigV1.config.getInstance((short)0);
				  List<Call> calls=new ArrayList<Call>();
				  String  tableName=Constants.HBASE_TBLNAME_IMSI_5G;
				  String   startrow=(Constants.HBASE_TBLNAME_IMSI_partition_start_5G
							+ imsi_new % Constants.HBASE_TBLNAME_IMSI_partition_5G) + "_" + imsi_new
							+ "_" + time_start;
				  String	endrow=(Constants.HBASE_TBLNAME_IMSI_partition_start_5G
							+ imsi_new % Constants.HBASE_TBLNAME_IMSI_partition_5G) + "_" + imsi_new
							+ "_" + time_end;
	 
				    System.out.println("startrow*****"+startrow);
					System.out.println("endrow*****"+endrow);
					
					System.out.println("tableName****"+tableName);
				  
				  Table table = conn.getTable(TableName.valueOf(tableName));
		            Scan scan = new Scan();
		            scan.setStartRow(startrow.getBytes());
		            scan.setStopRow(endrow.getBytes());
		            ResultScanner scanner = table.getScanner(scan);
		            int cellCount=0;
		            for (Result results : scanner) {
		            	String rowkey=new String(results.getRow());
		            	
		                for (Cell cell : results.rawCells()) {
		                    String row = cell.toString().split(":")[1].split("/")[0];
		                    byte[] bytes=CellUtil.cloneValue(cell);
		                    ByteBuffer byteBuf = ByteBuffer.wrap(bytes);
		                    Call call=new Call(callconfig,byteBuf);
		                    calls.add(call);
		                }
		            }
		            
		            for(Call call:calls) {
		  //  			System.out.println(call.toCallLine_m(Constants.sep, callconfig));
		    			Map<String, Object> map=new HashMap<>();
						map.put("result",call.toCallLine_m(Constants.sep, callconfig));
						result.add(map);
		            }
		            
		
			  }
		} catch (Exception e) {
			e.printStackTrace();
			 List<Map<String, Object>> error = new ArrayList<Map<String,Object>>();
			  Map<String, Object> retcodemap = new HashMap<>();
				retcodemap.put("retcode", "1");
				error.add(retcodemap);
				jsonString= JSON.toJSONString(error);
				e.printStackTrace();
				 return jsonString;
		}finally {
			try {
				conn.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
	System.out.println("result数据量****"+result.size());
		if(result.size()>0) {
			jsonString= JSON.toJSONString(result);
		}else {
			List<Map<String, Object>> error = new ArrayList<Map<String,Object>>();
			  Map<String, Object> retcodemap = new HashMap<>();
				retcodemap.put("retcode", "2");
				error.add(retcodemap);
				jsonString=JSON.toJSONString(error);
			
		}
		 
	//	System.out.println(jsonString);
		
		 return jsonString;
		
		
	}


	@Override
	public String getTrace_Signal(String json) {
		// TODO Auto-generated method stub
		 String jsonString="";
		 JSONObject object = JSONObject.parseObject(json);
		 String nettype= object.get("nettype").toString();//网络制式
		 String fName= object.get("fName").toString();  //文件名
		 long positions= Long.parseLong(object.get("position").toString()); //起始位置
		 long startTime= Long.parseLong(object.get("startTime").toString()); // 开始时间 时间戳
		 long endTime= Long.parseLong(object.get("endTime").toString());  // 结束时间 时间戳

		  System.out.println(nettype);
		  System.out.println(fName);
		  System.out.println(positions);
		  System.out.println(startTime);
		  
		  System.out.println(endTime);
		 
		 
		 
		 List<Map<String, Object>> list = new ArrayList<>();
		try {
			if(nettype.equalsIgnoreCase("4G")) {		
				LteCallMsgsHdfsQuery hdfs_read=new LteCallMsgsHdfsQuery(fName,positions,startTime,endTime);
				List<LteMessage> readList = hdfs_read.query();
				
				for(LteMessage msg:readList) {
					try {
						
			//			System.out.println(msg.getMessageText());
						Map<String, Object> map=new HashMap<>();
						map.put("msg", msg);
						list.add(map);
						//System.out.println(msg.getMessageText());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				Map<String, Object> retcodemap = new HashMap<>();
				retcodemap.put("retcode", "0");
				list.add(retcodemap);	
				
							
			}else if(nettype.equalsIgnoreCase("5G")) {
				CallMsgsHdfsQuery hdfs_read=new CallMsgsHdfsQuery(fName,positions,startTime,endTime);		
				List<SaMessage> readList = hdfs_read.query();
				for(SaMessage msg:readList) {
					try {
						Map<String, Object> map=new HashMap<>();
						map.put("msg", msg);
						list.add(map);
					//	System.out.println(msg.getMessageText());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				
				
				Map<String, Object> retcodemap = new HashMap<>();
				retcodemap.put("retcode", "0");
				list.add(retcodemap);
			}
		}catch (Exception e) {
			// TODO: handle exception
		
			 List<Map<String, Object>> error = new ArrayList<Map<String,Object>>();
			  Map<String, Object> retcodemap = new HashMap<>();
				retcodemap.put("retcode", "1");
				error.add(retcodemap);
				jsonString=JSON.toJSONString(error);
				e.printStackTrace();
				 return jsonString;
			 
		}
		  if(list.size()>0) {
			  jsonString= JSON.toJSONString(list);
		  }else {
			  List<Map<String, Object>> error = new ArrayList<Map<String,Object>>();
			  Map<String, Object> retcodemap = new HashMap<>();
				retcodemap.put("retcode", "2");
				error.add(retcodemap);
				jsonString=JSON.toJSONString(error);
		  }
		  System.out.println(jsonString);
        
		return jsonString;
	}



//
//	@Override
//	public String getHive_Data(String json)  {
//		// TODO Auto-generated method stub
//
//		 JSONObject object = JSONObject.parseObject(json);
//		 String sql= object.get("sql").toString();//sql 语句
//		  List<Map<String, Object>> resultList = new ArrayList<>();
//
//		    java.sql.Connection conn = null;
//	        Statement stmt = null;
//	        ResultSet rs = null;
//		  try  {
//			     conn = Hive_Utils.getConn();
//	             stmt = conn.createStatement();
//	              rs = stmt.executeQuery(sql);
//
//	            ResultSetMetaData rsmd = rs.getMetaData();
//	            int columnCount = rsmd.getColumnCount();
//
//	            while (rs.next()) {
//	                Map<String, Object> rowMap = new HashMap<>();
//	                for (int i = 1; i <= columnCount; i++) {
//	                    String columnName = rsmd.getColumnName(i);
//	                    Object columnValue = rs.getObject(i);
//	                    rowMap.put(columnName, columnValue);
//	                }
//	                resultList.add(rowMap);
//	            }
//	        } catch (Exception e) {
//	            e.printStackTrace();
//	        }finally {
//	            // 关闭资源
//	            if (rs != null) {
//                    try { rs.close(); } catch (SQLException ignore) {}
//                }
//	            if (stmt != null) {
//                    try { stmt.close(); } catch (SQLException ignore) {}
//                }
//	            if (conn != null) {
//                    try { conn.close(); } catch (SQLException ignore) {}
//                }
//	        }
//		String	jsonString= JSON.toJSONString(resultList);
//
//	        return jsonString;
//
//
//	}

	
	
    
}
